import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Http, URLSearchParams } from "@angular/http";
import { ActivatedRoute, Router } from "@angular/router";
import { Store } from "@ngrx/store";
import { sortFn } from "./../quote-table/utils";
import { Subject } from "rxjs/Subject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { TableOptions, QuoteHeaders } from "quote";
import { StockDetail } from "utils";
import { BASEURL } from "shared";
import * as _ from "lodash";

import {
  getId,
  ADD_NEW_TABLE,
  SET_SORT,
  UPDATE_DATA
} from "./../quote-table/quote-table-state";

import "./../../shared/rxjs-operators";

export const getParams = symbols => {
  return symbols.reduce((str, symbol) => `${str}symbol=${symbol}&`, "?");
};

export const BLOCK_HEADERS: QuoteHeaders = {
  headHeader: null,
  bodyHeader: [
    {
      label: "序号",
      key: "$order",
      class: ["order-cell", "text-left"]
    },
    {
      label: "名称",
      key: "name",
      class: ["text-left"]
    },
    {
      label: "股票代码",
      key: "symbol",
      class: ["text-left"]
    },
    {
      label: "现价",
      key: "current",
      withUpOrDown: true,
    },
    {
      label: "涨跌幅",
      key: "change_rate",
      withUpOrDown: true,
      withPercent: true,
      class: ["text-right"]
    },
    {
      label: "涨跌",
      key: "change_amount",
      withUpOrDown: true,
      class: ["text-right"]
    },
    {
      label: "成交量",
      key: "volume",
      withUnit: true
    },
    {
      label: "五分钟涨跌幅",
      key: "min5_change",
    },
    {
      label: "换手率",
      key: "turnover_ratio",
    },
    // {
    //   label: "周涨跌幅",
    //   key: "day5_change",
    // },
    // {
    //   label: "月涨跌幅",
    //   key: "day22_change",
    // },
  ]
}

export const BLOCK_STOCK_HEADERS: QuoteHeaders = {
  headHeader: null,
  bodyHeader: [
    {
      label: "序号",
      key: "$order",
      class: ["order-cell", "text-left"]
    },
    {
      label: "名称",
      key: "name",
      class: ["text-left"]
    },
    {
      label: "股票代码",
      key: "symbol",
      class: ["text-left"]
    },
    {
      label: "现价",
      key: "current",
      withUpOrDown: true,
    }, {
      label: "涨跌幅",
      key: "change_rate",
      withUpOrDown: true,
      withPercent: true
    }, {
      label: "涨跌",
      key: "change_amount",
      withUpOrDown: true,
    }, {
      label: "成交量",
      key: "volume",
      withUnit: true,
    }, {
      label: "换手率",
      key: "turnover_ratio",
      withPercent: true
    }, {
      label: "量比",
      key: "vol_ratio",
    }, {
      label: "委比",
      key: "entrust_rate",
    }, {
      label: "振幅",
      key: "amplitude",
    }, {
      label: "内盘",
      key: "amount_in",
    }, {
      label: "外盘",
      key: "amount_out",
    }, {
      label: "流通市值",
      key: "circulation_value",
      withUnit: true
    }
  ]
};

@Component({

  selector: 'quote-block',
  templateUrl: 'quote-block.component.html',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    'quote-block.component.less'
  ],
})
export class QuoteBlockComponent implements OnInit {
  params;
  blockParams;
  blockSub = new ReplaySubject(1);
  duration = 1;
  currentStock;
  currentStockSource = new ReplaySubject(1);
  blockTableHeaders = BLOCK_HEADERS;
  blockTableOptions: TableOptions = {
    afterGetData: data => data.filter(data => data.current !== 0 && data.volume),
    autoClickFirst: true,
    localSort: ["change_rate", "symbol", "change_amount", "current", "volume", "amount_in"],
    subscribe: {
      enabled: true,
      channels: ["dynPanel"]
    },
    responsive: {
      enabled: true,
      rowHeight: 30
    },
    parts: {
      pagination: true,
      order: true
    }
  };
  stockTableHeader = BLOCK_STOCK_HEADERS;
  stockTableOptions: TableOptions = {
    afterGetData: data => data.filter(data => data.current !== 0 && data.volume),
    autoClickFirst: true,
    minWidthOfBody: false,
    localSort: ["amplitude", "turnover_ratio", "amount_out", "circulation_value", "vol_ratio", "amplitude", "change_rate", "symbol", "change_amount", "current", "volume", "amount_in"],
    subscribe: {
      enabled: true,
      channels: ["dynPanel"]
    },
    responsive: {
      enabled: true,
    },
    parts: {
      pagination: true,
      order: true
    }
  };

  tabList = [
    {
      text: "概念板块",
      url: "/GN"
    },
    {
      text: "行业板块",
      url: "/HY"
    },
    {
      text: "地域板块",
      url: "/DY"
    }
  ];

  chartTabList = [
    {
      text: "分时",
      url: "/GN"
    },
    {
      text: "k线",
      url: "/HY"
    },
    // {
    //   text: "自选",
    //   url: "/DY"
    // }
  ];

  commonParams = {
    GN: {
      text: "概念板块",
      id: "GN",
      dataUrl: `${BASEURL}/stock/quotes/block?type=GN`
    },
    HY: {
      text: "行业板块",
      id: "HY",
      dataUrl: `${BASEURL}/stock/quotes/block?type=HY`
    },
    DY: {
      text: "地域板块",
      id: "DY",
      dataUrl: `${BASEURL}/stock/quotes/block?type=DY`
    },
  };

  constructor(private goRouter: Router, private router: ActivatedRoute, private http: Http) { }

  goCheckDetail(quote) {
    // console.debug("Quote Db Click: ", quote);
    this.goRouter.navigate([`/stock/${quote.symbol.replace(/\./, "_")}`]);
  }

  openBlock(quote) {
    this.blockSub.next(quote);
  }

  selectStock(stock) {
    this.currentStock = stock;
    this.currentStockSource.next(stock);
  }

  setDuration(duration) {
    this.duration = duration;
  }


  ngOnInit() {
    this.blockSub.subscribe(e => console.debug("Block SUB: ", e));
    this.blockParams = this.blockSub.switchMap(quote => {
      return this.http.get(`${BASEURL}/stock/block2symbols/${quote["symbol"]}`).map(res => res.json());
    }).map(res => {
      return {
        id: res.type,
        method: "post",
        body: {
          symbol: res.symbols
        },
        dataUrl: `${BASEURL}/stock/summaries/dynpanel`
      };
    }).publishReplay();
    this.blockParams.connect();

    this.params = this.router.params.map(params => {
      return this.commonParams[(<any>params).id] || this.commonParams["GN"];
    });
    this.params.subscribe(params => this.stockTableOptions = _.merge({}, this.stockTableOptions, { parts: { caption: params.text } }))
  }

}